/*
 * @Author: Drc
 * @Date: 2020-06-23 14:51:52
 * @LastEditors: Drc
 * @LastEditTime: 2021-03-25 09:53:28
 */
import {NavigationContainerRef} from '@react-navigation/native'
import React from 'react'
import {Params as LoginParams} from './LoginStack'
import {Params as MainParams} from './MainStack'
import {Stacks} from './index'
import {StackNavigationProp} from '@react-navigation/stack'

export const navigationRef = React.createRef<NavigationContainerRef>()

type RouteName = keyof LoginParams | keyof MainParams | Stacks

type Params<T> = LoginParams[T] & MainParams[T]

export default class NavigationController {
  //路由跳转
  static navigate<T extends RouteName>(name: T, params?: Params<T>) {
    navigationRef.current?.navigate(name, params)
  }

  //路由返回
  static pop = () => {
    navigationRef.current?.canGoBack() && navigationRef.current?.goBack()
  }

  //切换路由
  static replace = (name: Stacks) => {
    navigationRef.current?.resetRoot({index: 0, routes: [{name}]})
  }

  //获取参数
  static getParams<T extends RouteName>(routeName: T): Params<T> {
    const Route = navigationRef.current?.getRootState().routes[0]
    let result = {}

    for (let route of Route?.state?.routes ?? []) {
      if (route.name === routeName) {
        result = route.params ?? {}
        break
      }
    }

    return result as Params<T>
  }
}

type StackParams = {
  [P in RouteName]: Params<P> & {}
}

//路由接口
export interface RouteProps<T extends RouteName> {
  navigation: StackNavigationProp<StackParams>
  route: {
    name: T
    params: Params<T>
  }
}
